/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package merlion.common.session.stateless;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import merlion.common.entity.AuditLog;
import merlion.common.entity.SystemUserAccount;
import merlion.common.util.Consts;

/**
 *
 * @author Zhang Ying
 */
@Stateless
public class LogTrackingSessionBean implements LogTrackingSessionBeanLocal {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void updateLogInfo(String actionName, Long accId) {
        try {
            SystemUserAccount sua = entityManager.find(SystemUserAccount.class, accId);
            AuditLog alog = new AuditLog();
            alog.setActionName(actionName);
            Calendar calendar = Calendar.getInstance();
            Date date = calendar.getTime();
            Timestamp currentTime = new Timestamp(date.getTime());
            alog.setActionTime(currentTime);
            sua.getAuditLogs().add(alog);
            entityManager.merge(sua);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Collection<AuditLog> getAllLoggingLogs() {
        Query query = entityManager.createQuery("SELECT al FROM AuditLog al WHERE al.actionName=:p1 ORDER BY al.actionTime DESC");
        query.setParameter("p1", Consts.USER_LOGIN);
        return (List<AuditLog>) query.getResultList();
    }

    @Override
    public SystemUserAccount getAccountByLogId(Long logId) {
        AuditLog alog = entityManager.find(AuditLog.class, logId);
        Query query = entityManager.createQuery("SELECT sua FROM SystemUserAccount sua");
        Collection<SystemUserAccount> suas = query.getResultList();
        SystemUserAccount result = null;
        for (SystemUserAccount sua : suas){
            if (sua.getAuditLogs().contains(alog)){
                result = sua;
            }
        }
        return result;
    }

    @Override
    public String getLastLoginTimeString(Long accId) {
        SystemUserAccount sua = entityManager.find(SystemUserAccount.class, accId);
        List<AuditLog> logs = (List<AuditLog>) sua.getAuditLogs();
        int count = 0;
        for (int i = logs.size() -1; i>=0; i--){
            AuditLog alog = logs.get(i);
            if (count == 1){
                return alog.getFormattedDate();
            }
            if (alog.getActionName().equals(Consts.USER_LOGIN)){
                count++;
            }
        }
        return null;
    }
}
